package com.ugoodtech.mdcc.client.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.RequestObject.StationResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.GetLeanPaintKpiReportService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.KpiPaintReportVO.*;
import com.ugoodtech.mdcc.core.domain.KpiPaintReportVO.OperationalVO;
import com.ugoodtech.mdcc.core.domain.TechColorAuditingReports.TechColorAuditingReports;
import com.ugoodtech.mdcc.core.repository.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GetLeanPaintKpiReportServiceImpl implements GetLeanPaintKpiReportService {

    private Logger logger = LoggerFactory.getLogger(GetLeanPaintKpiReportServiceImpl.class);

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private AnswerDicRepository answerDicRepository;

    @Autowired
    private OperationalDataAnalysisRepository operationalDataAnalysisRepository;

    @Autowired
    private UnitOperationsRepository unitOperationsRepository;

    @Autowired
    private OverallOperationsRepository overallOperationsRepository;

    @Autowired
    private EconomicDataRepository economicDataRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private ReferenceRepository referenceRepository;

    @Autowired
    private StationPaintReportRepository stationPaintReportRepository;

    //保留2位小数 并转成String
    private String doubleGeTowDecimal(Double doubleNum) {
        DecimalFormat format = new DecimalFormat("0.00");
        String doubleStr = format.format(doubleNum);
        try {
            return new String(doubleStr.getBytes("UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "0.00";
        }
    }

    @Override
    public JsonResponse getLeanPaintKpiReport(Long reportId, Long stationId, User user) {
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.id.eq(reportId));
        builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
        builder.and(qStationReport.station.id.eq(stationId));
        StationReport stationReport = stationReportRepository.findOne(builder);
        UserProfile userProfile = userProfileRepository.findByUserId(stationReport.getUser().getId());
        //封装基本数据
        OperationalVO operationalVO = new OperationalVO();
        Station station = stationRepository.findOne(stationId);
        operationalVO.setStationName(station.getName());
        operationalVO.setAuditUser(userProfile.getRealName());
        String paintCompany = (String) stationColorReportRepository.getPaintCompany(stationId);
        if (StringUtils.isNotEmpty(paintCompany)) {
            operationalVO.setCompany(paintCompany);
        } else {
            operationalVO.setCompany("");
        }
        if (StringUtils.isNotEmpty(stationReport.getStation().getProvince()) && StringUtils.isNotEmpty(stationReport.getStation().getCity())) {
            operationalVO.setAddress(stationReport.getStation().getProvince() + stationReport.getStation().getCity());
        } else {
            operationalVO.setAddress("");
        }
        StationReport colorReport = stationReportRepository.selectReport(stationId);
        if (colorReport != null) {
            StationColorReport stationColorReport = stationColorReportRepository.selectReport(colorReport.getId(), 5L);
            if (stationColorReport != null) {
                operationalVO.setPhoto(stationColorReport.getAnswerPhoto());
            } else {
                operationalVO.setPhoto("");
            }
        } else {
            operationalVO.setPhoto("");
        }
        Date maxDateTime = (Date) operationalDataAnalysisRepository.getMaxDateTime(stationId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.CDATE_FORMAT);
        operationalVO.setDateTimeStr(simpleDateFormat.format(maxDateTime));
        StationPaintReport stationPaintReport = stationPaintReportRepository.selectAnswerByQuestion(stationReport.getId(), 62L);
        if (null != stationPaintReport && StringUtils.isNotEmpty(stationPaintReport.getAnswerOther())) {
            operationalVO.setCustomerUser(stationPaintReport.getAnswerOther());
        } else {
            operationalVO.setCustomerUser("");
        }


        /**
         * 封装精益板喷中填写的数据
         */
        List<Object[]> objArray = operationalDataAnalysisRepository.getDataKpi(reportId, stationId);
        if (objArray == null || objArray.size() == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "数据不全，请补完数据");
        }
        List<Object[]> listStr = toObjectResponse(operationalDataAnalysisRepository.getDataKpi(reportId, stationId));
        String[] nameStr = new String[10];
        nameStr[0] = "项目";
        nameStr[1] = "月喷漆产值（元）";
        nameStr[2] = "喷漆维修台次";
        nameStr[3] = "车间喷漆工人数";
        nameStr[4] = "车间喷涂工位数（不含烤房）";
        nameStr[5] = "平均单面喷漆收费";
        nameStr[6] = "油漆辅料实际使用金额（不含税）";
        nameStr[7] = "月漆工工资（元）";
        nameStr[8] = "烤房数量";
        nameStr[9] = "返工台次";
        operationalVO.setOperationalDataName(nameStr);
        operationalVO.setOperationalDataAnalysis(listStr);
        /**
         * 封装单元运营一览
         */
        listStr = toObjectResponse(unitOperationsRepository.getDataKpi(reportId, stationId));
        nameStr = new String[10];
        nameStr[0] = "项目";
        nameStr[1] = "单台车平均产值";
        nameStr[2] = "平均单车面数";
        nameStr[3] = "月均维修面数";
        nameStr[4] = "单工位维修台次/月";
        nameStr[5] = "单工位维修面数/月";
        nameStr[6] = "单工人维修台次/月";
        nameStr[7] = "单工人维修面数/月";
        nameStr[8] = "单工位产值（元）";
        nameStr[9] = "单工人产值（元）";
        operationalVO.setUnitOperationsName(nameStr);
        List<Object[]> unitOperationsReference = new ArrayList<>();
        Reference reference = null;
        //单台车平均产值
        if (listStr.get(listStr.size() - 1)[1] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[1]));
            if (value > 2299) {
                reference = referenceRepository.findOne(1L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(2L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            }
        }

        //平均单车面数
        if (listStr.get(listStr.size() - 1)[2] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[2]));
            if (value > 2.6D) {
                reference = referenceRepository.findOne(3L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(4L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            }
        }
        //月均维修面数
        String[] otherStr = new String[4];
        otherStr[0] = "月均维修面数";
        otherStr[1] = "";
        otherStr[2] = "";
        otherStr[3] = "";
        unitOperationsReference.add(otherStr);
        //单工位维修台次/月
        if (listStr.get(listStr.size() - 1)[4] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[4]));
            if (value > 45) {
                reference = referenceRepository.findOne(5L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(6L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            }
        }
        //单工位维修面数/月
        if (listStr.get(listStr.size() - 1)[5] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[5]));
            if (value > 75) {
                reference = referenceRepository.findOne(7L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(8L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            }
        }
        //单工人维修台次/月
        if (listStr.get(listStr.size() - 1)[6] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[6]));
            if (value > 60) {
                reference = referenceRepository.findOne(9L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(10L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            }
        }
        //单工人维修面数/月
        if (listStr.get(listStr.size() - 1)[7] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[7]));
            if (value > 120) {
                reference = referenceRepository.findOne(11L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(12L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                unitOperationsReference.add(str);
            }
        }
        //单工位产值
        otherStr = new String[4];
        otherStr[0] = "单工位产值";
        otherStr[1] = "";
        otherStr[2] = "";
        otherStr[3] = "";
        unitOperationsReference.add(otherStr);
        //单工人产值
        otherStr = new String[4];
        otherStr[0] = "单工人产值";
        otherStr[1] = "";
        otherStr[2] = "";
        otherStr[3] = "";
        unitOperationsReference.add(otherStr);

        operationalVO.setUnitOperations(listStr);
        operationalVO.setUnitOperationsReference(unitOperationsReference);

        /**
         * 封装总体产能一览
         */
        listStr = toObjectResponse(overallOperationsRepository.getDataKpi(reportId, stationId));
        nameStr = new String[10];
        nameStr[0] = "项目";
        nameStr[1] = "目前烤房最大产能（台）";
        nameStr[2] = "目前烤房最大产能（面）";
        nameStr[3] = "烤房利用率";
        nameStr[4] = "目前工人最大产能（台）";
        nameStr[5] = "目前工人最大产能（面）";
        nameStr[6] = "工人利用率";
        nameStr[7] = "目前工位最大产能（台）";
        nameStr[8] = "目前工位最大产能（面）";
        nameStr[9] = "工位利用率";
        operationalVO.setOverallOperationsName(nameStr);
        List<Object[]> overallOperationsReference = new ArrayList<>();
        List<Object[]> objects = toObjectResponse(overallOperationsRepository.getDataKpi(reportId, stationId));
        for (int i = 0; i < objects.size(); i++) {
            if (objects.get(i)[3].equals("") || objects.get(i)[6].equals("") || objects.get(i)[9].equals("")) {
                continue;
            }
            Double value = Double.valueOf(String.valueOf(objects.get(i)[3]));
            objects.get(i)[3] = doubleGeTowDecimal(value * 100) + "%";
            value = Double.valueOf(String.valueOf(objects.get(i)[6]));
            objects.get(i)[6] = doubleGeTowDecimal(value * 100) + "%";
            value = Double.valueOf(String.valueOf(objects.get(i)[9]));
            objects.get(i)[9] = doubleGeTowDecimal(value * 100) + "%";
        }
        operationalVO.setOverallOperations(objects);
        //目前烤房最大产能（台）
        if (listStr.get(listStr.size() - 1)[1] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[1]));
            if (value > 165) {
                reference = referenceRepository.findOne(13L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(14L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            }
        }
        //目前烤房最大产能（面）
        if (listStr.get(listStr.size() - 1)[2] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[2]));
            if (value > 450) {
                reference = referenceRepository.findOne(15L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(16L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            }
        }
        //烤房利用率
        if (listStr.get(listStr.size() - 1)[3] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[3]));
            if (value > 80) {
                reference = referenceRepository.findOne(17L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(18L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            }
        }
        //工人最大产能   台次/月
        if (listStr.get(listStr.size() - 1)[4] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[4]));
            if (value > 60) {
                reference = referenceRepository.findOne(35L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(36L);
                String[] str = new String[4];
                str[0] = reference.getResults();
                str[1] = reference.getAdvice();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            }
        }
        //工人最大产能   面数/月
        if (listStr.get(listStr.size() - 1)[5] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[5]));
            if (value > 120) {
                reference = referenceRepository.findOne(37L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(38L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            }
        }
        //工人利用率
        if (listStr.get(listStr.size() - 1)[6] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[6]));
            if (value > 80) {
                reference = referenceRepository.findOne(19L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(20L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            }
        }
        //目前工位最大产能（台）
        if (listStr.get(listStr.size() - 1)[4] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[7]));
            if (value > 45) {
                reference = referenceRepository.findOne(21L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(22L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            }
        }
        //目目前工位最大产能（面）
        if (listStr.get(listStr.size() - 1)[5] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[5]));
            if (value > 75) {
                reference = referenceRepository.findOne(23L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(24L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            }
        }
        //工位利用率
        if (listStr.get(listStr.size() - 1)[9] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[9]));
            if (value > 100) {
                reference = referenceRepository.findOne(25L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            } else {
                reference = referenceRepository.findOne(26L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                overallOperationsReference.add(str);
            }
        }
        operationalVO.setOverallOperationsReference(overallOperationsReference);
        /**
         * 经济性数据
         */
        listStr = toObjectResponse(economicDataRepository.getDataKpi(reportId, stationId));
        nameStr = new String[8];
        nameStr[0] = "项目";
        nameStr[1] = "返工率";
        nameStr[2] = "油漆成本占产值额比例";
        nameStr[3] = "人工成本占产值额比例";
        nameStr[4] = "单面材料成本";
        nameStr[5] = "单面人工成本";
        nameStr[6] = "车间毛利";
        nameStr[7] = "车间毛利率";
        operationalVO.setEconomicDataName(nameStr);
        List<Object[]> eonomicDataReference = new ArrayList<>();
        objects = toObjectResponse(economicDataRepository.getDataKpi(reportId, stationId));
        for (int i = 0; i < objects.size(); i++) {
            if (objects.get(i)[1].equals("") || objects.get(i)[2].equals("") || objects.get(i)[3].equals("") || objects.get(i)[7].equals("")) {
                continue;
            }
            Double value = Double.valueOf(String.valueOf(objects.get(i)[1]));
            objects.get(i)[1] = doubleGeTowDecimal(value * 100) + "%";
            value = Double.valueOf(String.valueOf(objects.get(i)[2]));
            objects.get(i)[2] = doubleGeTowDecimal(value * 100) + "%";
            value = Double.valueOf(String.valueOf(objects.get(i)[3]));
            objects.get(i)[3] = doubleGeTowDecimal(value * 100) + "%";
            value = Double.valueOf(String.valueOf(objects.get(i)[7]));
            objects.get(i)[7] = doubleGeTowDecimal(value * 100) + "%";
        }
        operationalVO.setEconomicData(objects);
        //返工率
        if (listStr.get(listStr.size() - 1)[1] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[1]));
            if (value < 2) {
                reference = referenceRepository.findOne(27L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                eonomicDataReference.add(str);
            } else {
                reference = referenceRepository.findOne(28L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                eonomicDataReference.add(str);
            }
        }
        //油漆成本占产值额比例
        otherStr = new String[4];
        otherStr[0] = "油漆成本占产值额比例";
        otherStr[1] = "";
        otherStr[2] = "";
        otherStr[3] = "";
        eonomicDataReference.add(otherStr);
        //人工成本占产值额比例
        otherStr = new String[4];
        otherStr[0] = "人工成本占产值额比例";
        otherStr[1] = "";
        otherStr[2] = "";
        otherStr[3] = "";
        eonomicDataReference.add(otherStr);
        //单面材料成本
        if (listStr.get(listStr.size() - 1)[4] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[4]));
            if (value > 105) {
                reference = referenceRepository.findOne(29L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                eonomicDataReference.add(str);
            } else {
                reference = referenceRepository.findOne(30L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                eonomicDataReference.add(str);
            }
        }
        //单面人工成本
        if (listStr.get(listStr.size() - 1)[5] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[5]));
            if (value > 80) {
                reference = referenceRepository.findOne(31L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                eonomicDataReference.add(str);
            } else {
                reference = referenceRepository.findOne(32L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                eonomicDataReference.add(str);
            }
        }
        //车间毛利
        otherStr = new String[4];
        otherStr[0] = "车间毛利";
        otherStr[1] = "";
        otherStr[2] = "";
        otherStr[3] = "";
        eonomicDataReference.add(otherStr);
        //车间毛利率
        if (listStr.get(listStr.size() - 1)[7] != null) {
            Double value = Double.valueOf(String.valueOf(listStr.get(listStr.size() - 1)[7]));
            if (value > 45) {
                reference = referenceRepository.findOne(33L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                eonomicDataReference.add(str);
            } else {
                reference = referenceRepository.findOne(34L);
                String[] str = new String[4];
                str[0] = reference.getReferenceName();
                str[1] = reference.getScope();
                str[2] = reference.getResults();
                str[3] = reference.getAdvice();
                eonomicDataReference.add(str);
            }
        }
        operationalVO.setEconomicDataReference(eonomicDataReference);

/////////////////////////////题目表格/////////////////////////////////////
        /**
         * 封装员工情况
         */
        List<Object[]> staff = Staff(reportId);
        /**
         * 封装总体情况
         */
        List<Object[]> general = General(reportId);
        /**
         * 封装喷漆车间
         */
        List<Object[]> paintShop = PaintShop(reportId);
        /**
         * 封装设备
         */
        List<Object[]> equipment = Equipment(reportId);
        /**
         * 封装钣喷车间流程
         */
        List<Object[]> shopsProcesses = ShopsProcesses(reportId);
        /**
         * 封装质量流程
         */
        List<Object[]> qualityProcesses = QualityProcesses(reportId);
        /**
         * 封装钣金车间
         */
        List<Object[]> bodyShop = BodyShop(reportId);
        bodyShop.addAll(staff);
        bodyShop.addAll(general);
        bodyShop.addAll(paintShop);
        bodyShop.addAll(equipment);
        bodyShop.addAll(shopsProcesses);
        bodyShop.addAll(qualityProcesses);
        operationalVO.setBodyShop(bodyShop);

//////////////////////////////柱状图////////////////////////////////////////////

//        Integer month = Integer.valueOf((String) operationalDataAnalysisRepository.getMaxImprovementStr(stationId));

        /**
         * 柱状图维修产值
         */
        List<Object[]> operationalData = operationalDataAnalysisRepository.getDataKpi(reportId, stationId);
        KpiArrayObject maintenanceValue = getKpiData(operationalData, Constants.MAINTENANCEVALUE);

        operationalVO.setMaintenanceValue(maintenanceValue);
        /**
         * 柱状图维修台次
         */
        KpiArrayObject maintenanceNum = getKpiData(operationalData, Constants.MAINTENANCENUM);
        operationalVO.setMaintenanceNum(maintenanceNum);


        /**
         * 柱状图单工位价值
         */
        List<Object[]> unitOperationsData = unitOperationsRepository.getDataKpi(reportId, stationId);
        KpiArrayObject workPersonValue = getKpiData(unitOperationsData, Constants.WORKPERSONVALUE);
        operationalVO.setWorkPersonValue(workPersonValue);
        /**
         * 柱状图单工人价值
         */
        KpiArrayObject personValue = getKpiData(unitOperationsData, Constants.PERSONVALUE);
        operationalVO.setPersonValue(personValue);


        /**
         * 柱状图材料成本
         */
        List<Object[]> economicData = economicDataRepository.getDataKpi(reportId, stationId);
        KpiArrayObject cost = getKpiData(economicData, Constants.COST);
        operationalVO.setCost(cost);
        /**
         * 柱状图人工成本
         */
        KpiArrayObject personCost = getKpiData(economicData, Constants.PERSONCOST);
        operationalVO.setPersonCost(personCost);
        /**
         * 柱状图返工率
         */
        KpiArrayObject reworkRate = getKpiData(economicData, Constants.REWORKRATE);
        operationalVO.setReworkRate(reworkRate);
        /**
         * 柱状图毛利率
         */
        KpiArrayObject grossProfitMargin = getKpiData(economicData, Constants.GROSSPROFITMARGIN);
        operationalVO.setGrossProfitMargin(grossProfitMargin);


        /**
         * 柱状图烤房利用率
         */
        List<Object[]> overallOperationsData = overallOperationsRepository.getDataKpi(reportId, stationId);
        KpiArrayObject brandUtilization = getKpiData(overallOperationsData, Constants.BRANDUTILIZATION);
        operationalVO.setBrandUtilization(brandUtilization);
        /**
         * 劳动利用率
         */
        KpiArrayObject laborUtilization = getKpiData(overallOperationsData, Constants.LABORUTILIZATION);
        operationalVO.setLaborUtilization(laborUtilization);
        /**
         * 工位利用率
         */
        KpiArrayObject stationUtilization = getKpiData(overallOperationsData, Constants.STATIONUTILIZATION);
        operationalVO.setStationUtilization(stationUtilization);

        return JsonResponse.successResponseWithData(operationalVO);
    }

    /**
     * 计算柱状图--改
     */
    private KpiArrayObject getKpiData(List<Object[]> kpiData, String statisticalType) {
        String[][] kpiArray = new String[2][kpiData.size()];
        for (int i = 0; i < kpiData.size(); i++) {
            if (kpiData.get(i)[kpiData.get(0).length - 1] == null) {
                continue;
            }
            String value = "";
            //维修产值  月喷漆产值
            if (statisticalType.equals(Constants.MAINTENANCEVALUE)) {
                logger.info("月喷漆产值：" + kpiData.get(i)[1]);
                value = String.valueOf(kpiData.get(i)[1]);
            }
            //工位价值  单工位价值
            if (statisticalType.equals(Constants.MAINTENANCENUM)) {
                logger.info("单工位价值：" + kpiData.get(i)[2]);
                value = String.valueOf(kpiData.get(i)[2]);
            }
            //工位价值  单工位价值
            if (statisticalType.equals(Constants.WORKPERSONVALUE)) {
                logger.info("单工位价值：" + kpiData.get(i)[8]);
                value = String.valueOf(kpiData.get(i)[8]);
            }
            //工人价值  单工人价值
            if (statisticalType.equals(Constants.PERSONVALUE)) {
                logger.info("单工人价值：" + kpiData.get(i)[9]);
                value = String.valueOf(kpiData.get(i)[9]);
            }
            //单面材料成本  单部件材料成本
            if (statisticalType.equals(Constants.COST)) {
                logger.info("单部件材料成本：" + kpiData.get(i)[4]);
                value = String.valueOf(kpiData.get(i)[4]);
            }
            //单面人工成本  单部件人工成本
            if (statisticalType.equals(Constants.PERSONCOST)) {
                logger.info("单部件人工成本：" + kpiData.get(i)[5]);
                value = String.valueOf(kpiData.get(i)[5]);
            }
            //返工率  返工率
            if (statisticalType.equals(Constants.REWORKRATE)) {
                logger.info("返工率：" + kpiData.get(i)[1]);
                value = String.valueOf(kpiData.get(i)[1]);
            }
            //毛利率  毛利率
            if (statisticalType.equals(Constants.GROSSPROFITMARGIN)) {
                logger.info("毛利率赋值：" + kpiData.get(i)[7]);
                value = String.valueOf(kpiData.get(i)[7]);
            }
            //烤房利用率  烤房利用率
            if (statisticalType.equals(Constants.BRANDUTILIZATION)) {
                logger.info("烤房利用率：" + kpiData.get(i)[3]);
                value = String.valueOf(kpiData.get(i)[3]);
            }
            //工人利用率  劳动利用率
            if (statisticalType.equals(Constants.LABORUTILIZATION)) {
                logger.info("劳动利用率：" + kpiData.get(i)[6]);
                value = String.valueOf(kpiData.get(i)[6]);
            }
            //工位利用率  工位利用率
            if (statisticalType.equals(Constants.STATIONUTILIZATION)) {
                logger.info("工位利用率：" + kpiData.get(i)[9]);
                value = String.valueOf(kpiData.get(i)[9]);
            }
            kpiArray[0][i] = value;
//            if (statisticalType.equals(Constants.MAINTENANCEVALUE)) {
//                kpiArray[0][i] = "";
//            }
//            if (statisticalType.equals(Constants.MAINTENANCENUM)) {
//                kpiArray[0][i] = "";
//            }
            if (kpiData.get(i)[kpiData.get(0).length - 1].equals(0)) {
                kpiArray[1][i] = "改善前3个月";
            }
            if (kpiData.get(i)[kpiData.get(0).length - 1].equals(1)) {
                kpiArray[1][i] = "改善前2个月";
            }
            if (kpiData.get(i)[kpiData.get(0).length - 1].equals(2)) {
                kpiArray[1][i] = "改善前1个月";
            }
            if (kpiData.get(i)[kpiData.get(0).length - 1].equals(3)) {
                kpiArray[1][i] = "改善当月";
            }
            if (kpiData.get(i)[kpiData.get(0).length - 1].equals(4)) {
                kpiArray[1][i] = "改善后1个月";
            }
            if (kpiData.get(i)[kpiData.get(0).length - 1].equals(5)) {
                kpiArray[1][i] = "改善后2个月";
            }
            if (kpiData.get(i)[kpiData.get(0).length - 1].equals(6)) {
                kpiArray[1][i] = "改善后3个月";
            }
        }
        KpiArrayObject kpiArrayObject = new KpiArrayObject();
        kpiArrayObject.setArray(kpiArray);
        Map<String, String> map = getPercentage(kpiArray, kpiData.size());
        kpiArrayObject.setUpDown(map);
        return kpiArrayObject;
    }


    @Override
    public List<Object[]> toArray(Long stationId, Long reportId) {
        List<Object[]> listStr = operationalDataAnalysisRepository.getDataKpi(stationId, reportId);
        Object[] obj = new Object[listStr.get(0).length];
        listStr.add(obj);
        Double aver = 0d;
        int x = 1;
        for (int j = 1; j < listStr.get(0).length; j++) {
            for (int i = 0; i < listStr.size() - 1; i++) {
                aver += Double.valueOf(String.valueOf(listStr.get(i)[j]));
                if (listStr.get(i)[listStr.get(0).length - 1].equals(0)) {
                    listStr.get(i)[0] = "改善前3个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(1)) {
                    listStr.get(i)[0] = "改善前2个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(2)) {
                    listStr.get(i)[0] = "改善前1个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(3)) {
                    listStr.get(i)[0] = "改善当月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(4)) {
                    listStr.get(i)[0] = "改善后1个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(5)) {
                    listStr.get(i)[0] = "改善后2个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(6)) {
                    listStr.get(i)[0] = "改善后3个月";
                }
            }
            listStr.get(listStr.size() - 1)[x++] = aver / (listStr.size() - 1);
            aver = 0d;
        }
        listStr.get(listStr.size() - 1)[0] = "平均值";
        return listStr;
    }


    /**
     * 公共返回表格方法
     *
     * @param listStr
     * @return
     */
    private List<Object[]> toObjectResponse(List<Object[]> listStr) {
        Object[] obj = new Object[listStr.get(0).length];
        listStr.add(obj);
        Double aver = 0d;
        int x = 1;
        int index = 0;
        for (int j = 1; j < listStr.get(0).length; j++) {
            for (int i = 0; i < listStr.size() - 1; i++) {
                if (listStr.get(i)[listStr.get(0).length - 1] == null) {
                    continue;
                }
                if (StringUtils.isEmpty(String.valueOf(listStr.get(i)[j]))) {
                    aver += 0;
                } else {
                    index++;
                    aver += Double.valueOf(String.valueOf(listStr.get(i)[j]));
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(0)) {
                    listStr.get(i)[0] = "改善前3个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(1)) {
                    listStr.get(i)[0] = "改善前2个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(2)) {
                    listStr.get(i)[0] = "改善前1个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(3)) {
                    listStr.get(i)[0] = "改善当月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(4)) {
                    listStr.get(i)[0] = "改善后1个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(5)) {
                    listStr.get(i)[0] = "改善后2个月";
                }
                if (listStr.get(i)[listStr.get(0).length - 1].equals(6)) {
                    listStr.get(i)[0] = "改善后3个月";
                }
            }
            if (aver == 0) {
                listStr.get(listStr.size() - 1)[x++] = 0.00;
            } else {
                DecimalFormat format = new DecimalFormat("#0.00");
                listStr.get(listStr.size() - 1)[x++] = format.format(aver / index);
            }
            index = 0;
            aver = 0d;
        }
        listStr.get(listStr.size() - 1)[0] = "平均值";
        return listStr;
    }

    private List<Object[]> getMonth(List<Object[]> listStr, List<Object[]> months) {
        Integer month = new Integer(months.get(0)[1].toString());
        for (int i = 0; i < listStr.size() - 1; i++) {
            Integer improvementTimStr = new Integer(listStr.get(i)[0].toString());
            Integer num = month - improvementTimStr;
            if (num == 0) {
                listStr.get(i)[0] = (Object) new String("改善当月");
            }
            if (num > 0) {
                listStr.get(i)[0] = (Object) new String("改善前" + num + "个月");
            }
            if (num < 0) {
                listStr.get(i)[0] = (Object) new String("改善后" + Math.abs(num) + "个月");
            }
        }
        return listStr;
    }

    private List<Object[]> QualityProcesses(Long reportId) {
        return answerDicRepository.statPatinReport(20L, reportId);
    }

    private List<Object[]> ShopsProcesses(Long reportId) {
        return answerDicRepository.statPatinReport(19L, reportId);
    }

    private List<Object[]> General(Long reportId) {
        return answerDicRepository.statPatinReport(24L, reportId);
    }

    private List<Object[]> BodyShop(Long reportId) {
        return answerDicRepository.statPatinReport(15L, reportId);
    }

    private List<Object[]> PaintShop(Long reportId) {
        return answerDicRepository.statPatinReport(16L, reportId);
    }

    private List<Object[]> Staff(Long reportId) {
        return answerDicRepository.statPatinReport(14L, reportId);
    }

    private List<Object[]> Equipment(Long reportId) {
        return answerDicRepository.statPatinReport(17L, reportId);
    }


    /**
     * 计算柱状图百分比
     */
    private Map<String, String> getPercentage(String[][] kpiArray, int size) {
        Map<String, String> map = new HashMap<>();
        Double before = 0d;
        Double after = 0d;
        int beforeIndex = 0;
        int aftereIndex = 0;
        for (int i = 0; i < size; i++) {
            if (StringUtils.isEmpty(kpiArray[0][i])) {
                continue;
            }
            if (StringUtils.isEmpty(kpiArray[1][i])) {
                continue;
            }
            if (kpiArray[1][i].indexOf("改善前") != -1) {
                if (kpiArray[0][i] != null && StringUtils.isNotEmpty(kpiArray[0][i]) && !kpiArray[0][i].equals("null")) {
                    before += Double.valueOf(kpiArray[0][i]);
                } else {
                    before += 0;
                }
                beforeIndex += 1;
            }
            if (kpiArray[1][i].indexOf("改善后") != -1) {
                if (kpiArray[0][i] != null && StringUtils.isNotEmpty(kpiArray[0][i]) && !kpiArray[0][i].equals("null")) {
                    before += Double.valueOf(kpiArray[0][i]);
                } else {
                    before += 0;
                }
                aftereIndex += 1;
            }
        }
        Double avagerAfter = 0d;
        if (aftereIndex == 0) {
            avagerAfter = 0d;
        } else {
            avagerAfter = after / aftereIndex;
        }

        Double avagerBefore = 0d;
        if (beforeIndex == 0d) {
            avagerBefore = 0d;
        } else {
            avagerBefore = before / beforeIndex;
        }

        if (avagerBefore == 0d) {
            map.put("维修产值", "0.00");
        } else {
            Double doubleNum = (avagerAfter - avagerBefore) / avagerBefore / 100;
            map.put("维修产值", doubleGeTowDecimal(doubleNum));
        }
        return map;
    }

    /**
     * 计算柱状改善月
     */
    private String getNum(Integer month, Integer improvementTimStr) {
        Integer num = month - improvementTimStr;
        if (num == 0) {
            return "改善当月";
        }
        if (num > 0) {
            return "改善前" + num + "个月";
        }
        if (num < 0) {
            return "改善后" + Math.abs(num) + "个月";
        }
        return null;
    }


    /**
     * 获取精益板喷KPI列表
     *
     * @param user
     * @param pageable
     * @param stationId
     * @param userId
     * @return
     */
    @Override
    public JsonResponse getPaintKpiList(User user, Pageable pageable, Long stationId, Long userId, String province, String city, String category, String brand,
                                        Long customerStat, Long customerType, String paintBrand, String productPosition) {
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        List<Nation> nationList = userProfile.getNationList();
        List<String> nationStr = new ArrayList<>();
        for (Nation nation : nationList) {
            nationStr.add(nation.getProvince());
        }
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        List<Long> list = new ArrayList<>();
        //判断是否是经销商
        if (user.getUserType().equals(UserType.dealers)) {
            if (stationId != null && stationId != 0) {
                builder.and(qStationReport.station.id.eq(stationId));
            } else {
                userProfile = userProfileRepository.findByUserId(user.getId());
                if (userProfile == null) {
                    return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户信息");
                }
                for (Station station : userProfile.getStationList()) {
                    list.add(station.getId());
                }
                builder.and(qStationReport.station.id.in(list));
            }
        } else {
            if (stationId != null && stationId != 0) {
                builder.and(qStationReport.station.id.eq(stationId));
            } else {
                if (StringUtils.isNotEmpty(province)) {
                    builder.and(qStationReport.station.province.eq(province));
                } else {
                    builder.and(qStationReport.station.province.in(nationStr));
                }
                if (StringUtils.isNotEmpty(city)) {
                    builder.and(qStationReport.station.city.eq(city));
                }
                if (StringUtils.isNotEmpty(category)) {
                    builder.and(qStationReport.station.category.eq(category));
                }
                if (StringUtils.isNotEmpty(brand)) {
                    builder.and(qStationReport.station.brand.eq(brand));
                }
            }
        }
        if (userId != null && userId != 0) {
            builder.and(qStationReport.user.id.eq(userId));
        }
        if (customerStat != null && customerStat != 0) {
            builder.and(qStationReport.station.customerStat.eq(customerStat));
        }
        if (customerType != null && customerType != 0) {
            builder.and(qStationReport.station.customerType.eq(customerType));
        }
        if (StringUtils.isNotEmpty(paintBrand)) {
            builder.and(qStationReport.station.paintBrand.like("%" + paintBrand + "%"));
        }
        if (StringUtils.isNotEmpty(productPosition)) {
            builder.and(qStationReport.station.productPosition.like("%" + productPosition + "%"));
        }
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<StationReport> stationReports = stationReportRepository.findAll(builder, pageable);
        List<TechColorAuditingReports> colorAuditingReports = toResponseVO(stationReports.getContent());
        Page<TechColorAuditingReports> page = new PageImpl(colorAuditingReports, pageable, colorAuditingReports.size());
        return JsonResponse.successResponseWithPageData(page);
    }


    /**
     * 封装返回类--改
     *
     * @param stationReports
     * @return
     */
    private List<TechColorAuditingReports> toResponseVO(List<StationReport> stationReports) {
        List<TechColorAuditingReports> reportsList = new ArrayList<>();
        for (StationReport report : stationReports) {
            TechColorAuditingReports techColorAuditingReports = new TechColorAuditingReports();
            techColorAuditingReports.setId(report.getId());
            techColorAuditingReports.setStationName(report.getStation().getName());
            techColorAuditingReports.setDateTime(report.getUpdateTimeStr());
            techColorAuditingReports.setStationId(report.getStation().getId());
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            if (userProfile == null) {
                techColorAuditingReports.setUserName("默认的名字");
            } else {
                techColorAuditingReports.setUserName(userProfile.getRealName());
            }
            if (null != report.getStation()) {
                if (StringUtils.isNotEmpty(report.getStation().getStationNum())) {
                    techColorAuditingReports.setStationNum(report.getStation().getStationNum());
                } else {
                    techColorAuditingReports.setStationNum("");
                }
                if (StringUtils.isNotEmpty(report.getStation().getCity()) && StringUtils.isNotEmpty(report.getStation().getProvince())) {
                    techColorAuditingReports.setCity(report.getStation().getProvince() + report.getStation().getCity());
                } else {
                    techColorAuditingReports.setCity("");
                }
            }
            StationRegularServiceReport regularServiceReport = stationRegularServiceReportRepository.selectQuestion(report.getId(), 155L);
            if (regularServiceReport == null) {
                techColorAuditingReports.setTarget("");
            } else {
                String targer = questionAnswerOptionRepository.findOne(Long.valueOf(regularServiceReport.getAnswerId())).getName();
                techColorAuditingReports.setTarget(targer);
            }
            if (StringUtils.isNotEmpty(report.getStation().getCategory())) {
                techColorAuditingReports.setStationType(report.getStation().getCategory());
            } else {
                techColorAuditingReports.setStationType("");
            }
            reportsList.add(techColorAuditingReports);
        }
        return reportsList;
    }

    /**
     * 获取筛选出的维修站
     *
     * @param user
     * @param province
     * @param city
     * @param brand
     * @param category
     * @param stationName
     * @param pageable
     * @return
     */
    @Override
    public JsonResponse getMyStation(User user, String province, String city, String brand, String category, String stationName, Pageable pageable) {
        QStation qStation = QStation.station;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStation.deleted.eq(false));
        builder.and(qStation.enabled.eq(true));
        if (StringUtils.isNotEmpty(province)) {
            builder.and(qStation.province.eq(province));
        } else {
            builder.and(qStation.province.in(getMyNation(user)));
        }
        if (StringUtils.isNotEmpty(city)) {
            builder.and(qStation.city.eq(city));
        }
        if (StringUtils.isNotEmpty(brand)) {
            builder.and(qStation.brand.eq(brand));
        } else {
            builder.and(qStation.brand.in(getMyBrand(user)));
        }
        if (StringUtils.isNotEmpty(category)) {
            builder.and(qStation.category.eq(category));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStation.name.like("%" + stationName + "%"));
        }
        Page<Station> stationPage = stationRepository.findAll(builder, pageable);
        List<StationResponse> stationResponses = toStationResponse(stationPage);
        Page<StationResponse> page = new PageImpl(stationResponses, pageable, stationPage.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    /**
     * 将筛选出来的维修站进行封装
     *
     * @param stationPage
     * @return
     */
    private List<StationResponse> toStationResponse(Page<Station> stationPage) {
        List<StationResponse> stationResponses = new ArrayList<>();
        for (Station station : stationPage.getContent()) {
            StationResponse stationResponse = new StationResponse();
            stationResponse.setId(station.getId());
            if (StringUtils.isEmpty(station.getName())) {
                continue;
            }
            stationResponse.setName(station.getName());
            stationResponses.add(stationResponse);
        }
        return stationResponses;
    }

    /**
     * 获取当前用户所负责的省份
     *
     * @param user
     * @return
     */
    private String[] getMyNation(User user) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qUserProfile.deleted.eq(false));
        booleanBuilder.and(qUserProfile.enabled.eq(true));
        booleanBuilder.and(qUserProfile.user.id.eq(user.getId()));
        UserProfile userProfile = userProfileRepository.findOne(booleanBuilder);
        Department department = userProfile.getDepartment();
        if (department == null) {
            return new String[0];
        }
//        List<Nation> nationList = department.getNationList();
//        String[] nationArray = new String[nationList.size()];
//        for (int i = 0; i < nationList.size(); i++) {
//            nationArray[i] = nationList.get(i).getProvince();
//        }
//        return nationArray;
        return null;
    }

    /**
     * 获取当前用户品牌
     *
     * @param user
     * @return
     */
    private String[] getMyBrand(User user) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qUserProfile.deleted.eq(false));
        booleanBuilder.and(qUserProfile.enabled.eq(true));
        booleanBuilder.and(qUserProfile.user.id.eq(user.getId()));
        UserProfile userProfile = userProfileRepository.findOne(booleanBuilder);
        Department department = userProfile.getDepartment();
        if (department == null) {
            return new String[0];
        }
//        List<Brand> brandList = department.getBrandList();
//        String[] brandArray = new String[brandList.size()];
//        for (int i = 0; i < brandList.size(); i++) {
//            brandArray[i] = brandList.get(i).getBrandName();
//        }
//        return brandArray;
        return null;
    }

    /**
     * 获取筛选出的技术人员
     *
     * @param user
     * @param userName
     * @param pageable
     * @return
     */
    @Override
    public JsonResponse getMyUser(User user, String userName, Pageable pageable) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        if (StringUtils.isNotEmpty(userName)) {
            builder.and(qUserProfile.realName.like("%" + userName + "%"));
        }
//        builder.and(qUserProfile.department.nationList.any().province.in(getMyNation(user)));
        Page<UserProfile> userProfilePage = userProfileRepository.findAll(builder, pageable);
        List<StationResponse> stationResponses = toUserResponse(userProfilePage);
        Page<StationResponse> page = new PageImpl(stationResponses, pageable, userProfilePage.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    /**
     * 将筛选出来的技术人员进行封装
     *
     * @param userProfilePage
     * @return
     */
    private List<StationResponse> toUserResponse(Page<UserProfile> userProfilePage) {
        List<StationResponse> stationResponseList = new ArrayList<>();
        for (UserProfile user : userProfilePage.getContent()) {
            StationResponse userResponse = new StationResponse();
            userResponse.setId(user.getUser().getId());
            if (StringUtils.isEmpty(user.getRealName())) {
                continue;
            }
            userResponse.setName(user.getRealName());
            stationResponseList.add(userResponse);
        }
        return stationResponseList;
    }


}


